<!--
 * @Description: 角色管理页面
-->
<template>
  <!-- <BaseMainSlot class="patrol-point-manage">
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-show="activeName === '1'">收起筛选</p>
              <p v-show="activeName === ''">展开筛选</p>
            </div>
          </template>
<div class="search-btn search-btns" @click.stop="getTableDataList()">
  <i class="el-icon-circle-check"></i>
  <p>查询</p>
</div>
<div class="select-box-content">
  <div class="select-box-content-name">角色名称：</div>
  <el-input v-model="roleName" clearable placeholder="请输入角色名称" @change="getTableDataList()" />
</div>
</el-collapse-item>
</el-collapse>
</template>
<template v-slot:btnsBar>
      <ActionBar :page-no="175" :add-active="addActive" :del-active="delActive" :has-app-auth="true"
        :has-func-auth="true" @add="add" @del="del" :func-auth-active="funcAuthActive"
        :func-app-auth-active="funcAppAuthActive" @funcAuth="funcAuthShow" @funcAppAuth="funcAppAuthShow"
        @edit="edit" />
    </template>
<template v-slot:content>
      <el-table ref="tableData" highlight-current-row v-loading="loading" :data="tableData" stripe border
        height="calc(100% - 50px)" :row-key="row => { return row.roleId; }" @row-click="handleEdit"
        @selection-change="handleSelectionChange" @select="select" @select-all="selectAll">
        <el-table-column type="selection" width="55" :reserve-selection="true"
          :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.roleId ? scoped.$index + 1 : "" }}
          </template>
</el-table-column>
<el-table-column prop="roleId" label="角色ID" />
<el-table-column prop="roleName" label="角色名称" />
<el-table-column width="200" label="操作">
  <template v-if="scoped.row.roleId" slot-scope="scoped">
            <div class="table-btns-box">
              <div class="table-btns edit-btns" @click="edit(scoped.row.roleId)">
                <i class="el-icon-edit-outline"></i>
                <p>修改</p>
              </div>
              <div class="table-btns del-btns" @click="delOne(scoped.row.roleId)">
                <i class="el-icon-delete"></i>
                <p>删除</p>
              </div>
            </div>
          </template>
</el-table-column>
</el-table>
<Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize"
  @changeCurrentPage="changeCurrentPage" />
<div class="el-dialog">
  <el-dialog :title="titleText + '角色'" :visible.sync="dialogFormVisible" width="40%" :before-close="cancel"
    :close-on-click-modal="false">
    <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
      <el-form-item label="角色名称:" prop="roleName" class="w100p">
        <el-input v-model="formData.roleName" clearable />
      </el-form-item>
    </el-form>
    <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
      <el-button class="cancelbtn" @click="cancel('formData')">
        取 消
      </el-button>
      <el-button class="savebtn" type="primary" @click="save('formData')">
        保 存
      </el-button>
    </div>
  </el-dialog>
  <el-dialog title="分配功能权限" :visible.sync="dialogDataAuthFormVisible" width="40%" height="65%" :before-close="cancel"
    :close-on-click-modal="false">

    <el-tree node-key="functionPermissionId" ref="tree" @check-change="handleCheckChange" show-checkbox :data="treeData"
      :props="defaultProps" accordion>
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button class="cancelbtn" @click="cancel"> 取 消 </el-button>
      <el-button class="savebtn" type="primary" @click="updatePermission">
        保 存
      </el-button>
    </div>
  </el-dialog>
  <el-dialog title="分配App功能权限" :visible.sync="dialogDataAppAuthFormVisible" width="40%" :close-on-click-modal="false"
    :before-close="cancel">
    <el-tree node-key="functionPermissionId" ref="treeApp" @check-change="handleCheckChangeApp" show-checkbox
      :data="treeDataApp" :props="defaultPropsApp">
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button class="cancelbtn" @click="cancel"> 取 消 </el-button>
      <el-button class="savebtn" type="primary" @click="updatePermissionApp">
        保 存
      </el-button>
    </div>
  </el-dialog>
</div>
</template>
</BaseMainSlot> -->
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="search">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <!-- 表格 -->
      <el-table ref="tableData" highlight-current-row v-loading="loading" :data="tableData" stripe border
        :row-key="row => { return row.roleId; }" @row-click="handleEdit" @selection-change="handleSelectionChange"
        @select="select" @select-all="selectAll">
        <el-table-column type="selection" width="55" :reserve-selection="true"
          :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.roleId ? scoped.$index + 1 : "" }}
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column width="400" label="操作">
          <template slot-scope="scoped">
            <span class="table-btns del-btns successText" @click="funcAuthShow(scoped.row.roleId)">分配功能权限</span>
            <span class="table-btns del-btns successText" @click="funcAppAuthShow(scoped.row.roleId)">分配App功能权限</span>
            <span class="table-btns edit-btns successText" @click="edit(scoped.row.roleId)">修改</span>
            <span class="table-btns del-btns errorText" @click="delOne(scoped.row.roleId)">删除</span>

          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <!-- 模态框 -->
      <el-dialog :title="titleText + '角色'" :visible.sync="dialogFormVisible" width="40%" :before-close="cancel"
        :close-on-click-modal="false">
        <el-form ref="formData" :model="formData" :rules="rules" label-width="120px" class="demo-ruleForm">
          <el-form-item label="角色名称:" prop="roleName" class="w100p">
            <el-input v-model="formData.roleName" clearable />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <!-- 功能权限 -->
      <el-dialog title="分配功能权限" :visible.sync="dialogDataAuthFormVisible" width="40%" height="65%"
        :before-close="cancel" :close-on-click-modal="false">
        <!-- 1.web端树 -->
        <div class="tree">
          <div class="tagList">
            <div @click="getAllPermission()" :class="sysType == 1 ? 'activeTag' : ''">生产模块</div>
            <div @click="chooseSysType(2, 'WEB')" :class="sysType == 2 ? 'activeTag' : ''">NC模块</div>
          </div>
          <div class="treeData">
            <el-tree v-if="resetTree" node-key="functionPermissionId" ref="tree" @check-change="handleCheckChange"
              show-checkbox :data="newtreeData" :props="defaultProps" accordion>
            </el-tree>
          </div>
        </div>
        <!-- footer -->
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel"> 取 消 </el-button>
          <el-button class="savebtn" type="primary" @click="updatePermission">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <!-- 2.app权限 -->
      <el-dialog title="分配App功能权限" :visible.sync="dialogDataAppAuthFormVisible" width="40%"
        :close-on-click-modal="false" :before-close="cancel">
        <div class="tree">
          <div class="tagList">
            <div @click="getAppPermission()" :class="sysType == 1 ? 'activeTag' : ''">生产模块</div>
            <div @click="chooseSysType(2, 'APP')" :class="sysType == 2 ? 'activeTag' : ''">NC模块</div>
          </div>
          <div class="treeData">
            <el-tree v-if="resetTree" node-key="functionPermissionId" ref="treeApp" @check-change="handleCheckChangeApp"
              show-checkbox :data="newtreeData" :props="defaultPropsApp">
            </el-tree>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel"> 取 消 </el-button>
          <el-button class="savebtn" type="primary" @click="updatePermissionApp">
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import BtnSlot from '@/components-production-management/BtnSlot';

import DataAuthComponent from "../components/func-auth-component.vue";
import DataAppAuthComponent from "../components/App-auth-component.vue";
import { mymixin } from "@/utils/kingmixin.js";
import { mapGetters } from "vuex";
import RoleApi from "@/api/system-settings/role-manage"

export default {
  name: "role-manage",
  components: {
    BtnSlot,
    Pagination,
    SearchForm,
    DataAuthComponent,
    DataAppAuthComponent,
    MainSlot,
  },
  // 混入
  mixins: [mymixin],
  data() {
    return {
      btnList: ['add', 'delete'],
      formItemList: [
        {
          label: '角色名称',
          type: 'input',
          param: 'roleName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
      ],
      authedIds: [],
      authedIdsApp: [],
      treeData: [],//web端all权限,
      newtreeData: [],
      defaultProps: {
        children: 'childList',
        label: 'funcName',
        isLeaf: 'leaf'
      },
      treeDataApp: [],//app端all权限
      defaultPropsApp: {
        children: 'childList',
        label: 'funcName'
      },
      checkedKeysApp: [],
      checkedKeys: [],
      // 操作按钮的逻辑及展示数据
      addActive: true,
      editActive: false,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      dataAuthActive: false,
      funcAuthActive: false,//web
      funcAppAuthActive: false,//app
      dialogDataAppAuthFormVisible: false,
      // table
      loading: true,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 角色名称
      roleName: "",
      nowpage: 1,
      // 是否能输入
      canInput: false,
      tableData: [],
      rolestu: "",
      formData: {},
      resetTree: true,
      checkedIdList: [],
      sysType: 1,
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      // 选中的数据项数组 ID组成
      selectedRoleId: '',
      roleIdList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      dialogDataAuthFormVisible: false,
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  created() {
    // 获取表格数据
    this.getTableDataList();
  },
  mounted() {
    // let rst = this.formatMenuData(asyncRoutes)
    // this.treeData = rst
    // 获取web端整个数据
    this.getAllPermission()
    this.getAppPermission()
  },
  methods: {
    chooseSysType(sysType, sysFlag) {
      this.sysType = sysType;
      this.getPermissionByRoleId(sysFlag);
      let treeList = sysFlag == 'WEB' ? JSON.parse(JSON.stringify(this.treeData)) : this.treeDataApp
      if (sysType == 1) {
        this.newtreeData = this.filterNc(treeList, false)
        console.log(this.filterNc(treeList, false), false)
      } else {
        console.log('菜单',treeList)
        this.newtreeData = this.filterNc(treeList, true)
        console.log(this.filterNc(treeList, true), true)
      };
      this.resetTree = false;
      this.$nextTick(() => {
        this.resetTree = true;
      })
    },
    filterNc(list, flag) {
      let that = this;
      let routerList = [];
      list.forEach(item => {
        let isNcQuery = item.isNcQuery;
        let isBooblean = typeof isNcQuery == 'boolean';
        // console.log(item.funcName,item.childList)
        if (isBooblean) {
          if (isNcQuery == flag) {
            if (item.childList && item.childList.length > 0) {
              item.childList = that.filterNc(item.childList, flag)
            }
            routerList.push(item);
          }
        } else {
          if (item.childList && item.childList.length > 0) {
            item.childList = that.filterNc(item.childList, flag)
          }
          routerList.push(item);
        }
      })
      return routerList
    },
    search(data) {
      this.roleName = data.roleName;
      this.getTableDataList();
    },
    // k2.通过角色id查询功能权限列表
    getPermissionByRoleId(type = "WEB") {
      this.authedIds = []
      this.authedIdsApp = []
      RoleApi.queryRoleFuncList({ roleId: this.selectedRoleId, funcType: type }).then(res => {
        if (res) {
          if (type == "WEB") {
            this.authedIds = this.formateAuthId(res.data)
          } else {//app
            this.authedIdsApp = this.formateAuthApp(res.data)
          }
        }
      })
    },
    // k3.处理k2中角色的权限
    async formateAuthId(pers) {
      // 如果选中的长度为零
      let rst = []
      if (pers.length == 0) {
        await this.$nextTick(() => {
          // node设置
          this.$refs.tree.setCheckedNodes([]);
        });
        return []
        // 不为零
      } else {
        pers = pers.filter((per) => {
          rst.push(per.functionPermissionId)
          if (per.childList) {
            this.formateAuthId(per.childList, rst)
          }
          return per.pid != 0
        })
        await this.$nextTick(() => {
          this.$refs.tree.setCheckedNodes(pers);
        });
        return rst
      }
    },
    async formateAuthApp(pers) {
      let rst = []
      if (pers.length == 0) {
        await this.$nextTick(() => {
          // node设置
          this.$refs.treeApp.setCheckedNodes([]);
        });
        return []
      } else {
        pers.forEach((per) => {
          rst.push(per.functionPermissionId)
          if (per.childList) {
            this.formateAuthApp(per.childList, rst)
          }
        })
        await this.$nextTick(() => {
          this.$refs.treeApp.setCheckedNodes(pers);
        });
        return rst
      }
    },
    // k1.web端权限
    getAllPermission() {
      let params = {
        funcType: 'WEB'
      }
      RoleApi.getAllPermissionByFuncType(params).then((res) => {
        this.loading = false;
        this.treeData = res.data;
        console.log('菜单',res.data)
        this.chooseSysType(1, 'WEB');
      });
    },
    // app端
    getAppPermission() {
      let params = {
        funcType: 'APP'
      }
      RoleApi.getAllPermissionByFuncType(params).then((res) => {
        this.loading = false;
        this.treeDataApp = res.data
        this.chooseSysType(1, 'APP');
      });
    },
    // k4.添加web端权限
    updatePermission() {
      let pers = this.checkedKeys
      pers = [...this.$refs.tree.getHalfCheckedKeys(), ...pers]
      let params = {
        funcIdList: pers,
        roleId: this.selectedRoleId,
        funcType: 'WEB'
      }
      if (pers.length >= 0 && this.selectedRoleId) {
        RoleApi.addFuncList(params).then((res) => {
          this.$message.success(res.message || '操作成功');
          this.dialogDataAuthFormVisible = false
        })
      }
    },
    updatePermissionApp() {
      let pers = this.checkedKeysApp
      let params = {
        funcIdList: pers,
        roleId: this.selectedRoleId,
        funcType: 'APP'
      }
      if (pers.length >= 0 && this.selectedRoleId) {
        RoleApi.addFuncList(params).then((res) => {
          this.$message.success(res.message || '操作成功');
          this.dialogDataAppAuthFormVisible = false
        })

      } else {

      }
    },
    getAllPath(nodes, rst = []) {
      nodes.forEach(node => {
        if (!node.children) {
          rst.push(node.path)
        } else {
          this.getAllPath(node.children, rst)
        }
      })
      return rst
    },
    // k6.web选择权限--节点选中状态发生变化时的回调
    handleCheckChange(data, checked, indeterminate) {
      let checkedKeys = this.$refs.tree.getCheckedKeys()
      this.checkedKeys = checkedKeys
    },
    handleCheckChangeApp(data, checked, indeterminate) {
      let checkedKeys = this.$refs.treeApp.getCheckedKeys()
      this.checkedKeysApp = checkedKeys
    },
    formatMenuData(data) {
      return data.map(val => {
        if (val.children && val.children.length > 0) {
          return {
            label: val.meta.title,
            path: val.path,
            children: this.formatMenuData(val.children)
          }
        } else {
          return {
            path: val.path,
            label: val.meta.title
          }
        }
      })
    },
    // 1.获取表格数据
    async getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          homeBaseType: 1
        }
      };
      // king查询
      if (this.roleName) {
        params.entity.roleName = this.roleName
        params.entity.page = 1
        this.currentPage = 1
      }
      let res = await RoleApi.queryPageByCondition(params)
      if (res.success) {
        this.loading = false;
        let data = res.data || [];
        // 赋值总条数
        this.totalSize = data.totalElements || 0;
        // 赋值数组
        this.tableData = data.content || [];
        this.dialogFormVisible = false;
      }
    },
    saveRole() {
      this.rolestu = "add";
    },
    roles() {
      this.rolestu = "";
      this.dialogDataAuthFormVisible = false;
      this.dialogDataAppAuthFormVisible = false;
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // k0.点击行触发
    handleEdit(row) {
      this.checkedKeys = []
      this.selectedRoleId = row.roleId
      this.formData = JSON.parse(JSON.stringify(row));
    },
    selectAll(list) {
      this.funcAuthActive = false
      this.funcAppAuthActive = false
    },
    select(list) {
      // 判断按钮是否显示
      if (list.length == 1 && list[0].roleId) {
        let id = list[0].roleId
        this.selectedRoleId = id
        this.funcAuthActive = true;
        this.funcAppAuthActive = true;
      } else {
        this.funcAuthActive = false
        this.funcAppAuthActive = false
      }
      let notvalue = true
      list.forEach(item => {
        if (!item.roleId) {
          notvalue = false;
          return
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    // 复选框变化
    handleSelectionChange(list) {
      this.checkedIdList = [];
      this.checkedIdList = list.map(item => {
        if (item.roleId) {
          return item.roleId
        } else {
          return ""
        }
      });
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 点击功能权限触发的方法
    funcAuthShow(id) {
      this.selectedRoleId = id;
      this.dialogDataAuthFormVisible = true;
      this.getPermissionByRoleId('WEB');
      this.getAllPermission();
    },
    // 点击app功能权限触发
    funcAppAuthShow(id) {
      this.selectedRoleId = id;
      this.dialogDataAppAuthFormVisible = true;
      this.getPermissionByRoleId('APP');
      this.getAppPermission()
    },
    cancel() {
      this.closeDialog();
      this.addActive = true
      this.formData = {};
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignUserActive = false;
      this.funcAppAuthActive = false;
      this.dialogDataAuthFormVisible = false;
      this.dialogDataAppAuthFormVisible = false;
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.formData.roleId) {
            // 编辑接口
            RoleApi.edit(this.formData).then((res) => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.formData = {};
                this.getTableDataList();
              }
            });
          } else {
            // 新增接口
            this.formData.homeBaseType = 1;
            RoleApi.add(this.formData).then((res) => {
              if (res.success === true) {
                this.addActive = true
                this.$message.success("新增成功！");
                this.formData = {};
                this.getTableDataList();
              } else {
                this.$message.error(res.message)
              }
            });
          }
        } else {
          return false;
        }
        if (this.formData.id && this.nowpage === 2) {
          this.$refs.funcAuth.setpermission();
        } else if (this.nowpage === 3) {
          this.$refs.assignrole.checkchange();
        }
      });
    },

    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage();
      }
    },
    // 单个删除
    delOne(id) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          RoleApi.delById({ id: id }).then(res => {
            if (res.success === true) {
              this.$message.success("删除成功！");
              if ((this.totalSize - 1) % 10 == 0) {
                this.currentPage--
                this.getTableDataList();
              } else {
                this.getTableDataList()
              }
            }
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        })
    },

    // king表格删除
    delmessage() {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          RoleApi.delByListId({ idList: this.checkedIdList }).then(res => {
            if (res.success) {
              if ((this.totalSize - this.checkedIdList.length) % 10 == 0) {
                this.currentPage--
                this.getTableDataList();
              } else {
                this.getTableDataList()
              }
              this.$message.success("删除成功");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        })

    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
  },
};
</script>
<style lang="scss" scoped>
.table-btns {
  padding: 0 10px;
  cursor: pointer;
}

.imageStyle {
  height: 100px;
  width: 200px;
  border-radius: 4px;
  margin: 0 auto;
  background-color: #cecece3f;
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-size: 16px;
  color: #999999;
}

.tree {
  max-height: 600px;
  overflow: auto;

  .tagList {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 30px;

    div {
      padding: 10px 20px;
      color: #999999;
      cursor: pointer;
      background-color: #ffffff;
    }

    .activeTag {
      color: #17b9e2;
      background-color: #f3f3f3;
    }
  }



  .treeData {
    background-color: #f3f3f3;
  }
}
</style>
